<template>
  <div style="padding-bottom: 20px" v-if="editOpen">
    <t-loading size="small" :loading="loading" showOverlay>
      <t-form ref="form"  :data="formData" labelAlign="top" labelWidth="100px" :rules="rules">
        <t-form-item label="诚信承诺函签名日期：" name="signDate">
          <t-date-picker clearable  v-model="formData.signDate"></t-date-picker>
        </t-form-item>
        <t-form-item :show-error-message="false" style="align-items: flex-start" v-if="expertEditOpen" label="科研诚信承诺书：" name="zjkCnsIds">
          <template slot="label">
            科研诚信承诺书：<t-link hover="color" :underline="false"  theme="primary"  @click="downloadTemp">模版下载</t-link>
            <t-link hover="color" :underline="false"  theme="primary"  :loading="refreshStart" @click="createTemp" variant="outline">
              {{refreshStart?'自动生成带签名的诚信承诺书中...':'自动生成诚信承诺书'}}
            </t-link>

            <t-popup trigger="click">
              <t-link hover="color" style="margin-left: 10px" :underline="false"  theme="primary" >扫码更新签名</t-link>
              <template #content>
                <h3>手机扫码更新签名</h3>
                <qrcode-vue  :value="qrcodeValue" :size="192" level="H" />
              </template>
            </t-popup>
          </template>
          <file-upload v-model="formData.zjkCnsIds" accept="application/pdf" moduleKey="zjkCns" :fileList="zjkCnsFiles"
                       :multiple="false" tips="">
            <t-button variant="outline">
              <t-icon name="cloud-upload" slot="icon"/>
              上传诚信承诺书
            </t-button>
          </file-upload>
        </t-form-item>
        <t-form-item :show-error-message="false" label="评审意见和建议：" name="content">
          <template slot="label">
            评审意见和建议(可通过附件上传)：
          </template>
          <t-textarea
            clearable :autosize="{minRows: 5}"
            v-model="formData.content"
            placeholder="请输入内容"
          />
        </t-form-item>

        <t-form-item style="margin-bottom: 14px" label="评审意见和建议附件：" name="zjkYJ">
          <file-upload  v-model="formData.zjkYJIds"  moduleKey="zjkYJ" :fileList="zjkYJFiles"
                        :multiple="false" tips="">
            <t-button variant="outline">
              <t-icon name="cloud-upload" slot="icon"/>
              上传
            </t-button>
          </file-upload>
        </t-form-item>
        <t-form-item label="是否通过：" name="projectApproval">
          <t-radio-group  v-model="formData.projectApproval">
            <t-radio value="1">是</t-radio>
            <t-radio value="2">需要复议</t-radio>
            <t-radio value="0">否</t-radio>
          </t-radio-group>
        </t-form-item>
      </t-form>
    </t-loading>
  </div>
  <div style="padding-bottom: 20px" v-else>
    <t-loading size="small" :loading="loading" showOverlay>
      <t-form  ref="form" :data="formData" labelAlign="top" labelWidth="100px" :rules="rules">
        <t-form-item label="诚信承诺函签名日期：" name="signDate">
          {{formData.signDate}}
        </t-form-item>
        <t-form-item style="margin-bottom: 14px" label="科研诚信承诺书：" name="zjkCnsIds">
          <a class="t-button-link" target="_blank" v-if="zjkCnsFiles.length>0" :href="zjkCnsFiles[0].url">
            {{ zjkCnsFiles[0].name }}
          </a>
        </t-form-item>
        <t-form-item label="评审意见和建议(可通过附件上传)：" name="content">
          {{formData.content}}
        </t-form-item>
        <t-form-item style="margin-bottom: 14px" label="评审意见和建议附件：" name="zjkYJ">
          <a class="t-button-link" target="_blank" v-for="(item,index) in zjkYJFiles" :href="item.url"
             :key="index">
            {{ item.name }}
          </a>
        </t-form-item>
        <t-form-item label="是否通过：" name="projectApproval">
          <t-radio-group disabled v-model="formData.projectApproval">
            <t-radio value="1">是</t-radio>
            <t-radio value="2">需要复议</t-radio>
            <t-radio value="0">否</t-radio>
          </t-radio-group>
        </t-form-item>
      </t-form>
    </t-loading>
  </div>

</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import FileUpload from "@/components/FileUpload/index.vue"
import {getFilesByUserId} from "@/api/common";
import QrcodeVue from 'qrcode.vue';
import {getToken} from "@/utils/auth";
import { TODAY_CN, TODAY } from '@/utils/date';


export default {
  name: "edit-project-expert-review",
  components: {
    FileUpload,
    QrcodeVue
  },
  props: {
    objId: [Number, String],
    teamId: [Number, String],
    reviewType: [Number, String],
    expertUserId: [Number, String],
    editOpen: {
      type: Boolean,
      default: true
    },
    expertEditOpen: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      refreshStart: false,
      qrcodeValue: '',
      signDialog: {
        open: false,
        signId: 0,
        file: {}
      },
      sign: false,
      totalScore: 0,
      loading: true,
      visible: true,
      fileLists: [],
      zjkCnsFiles: [],
      zjkYJFiles: [],
      contentType: '1',
      formData: {
        id: this.objId,
        projectApproval: '1',
        score: null,
        content: '',
        projectItemScores: [],
        sysAttMainVo: {
          sysAttMainIds: []
        },
        zjkCnsIds: [],
        zjkYJIds: [],
        zjkSign: [],
        signatureFiles: [],
        recommendType: '1',
        signDate: TODAY
      },
      rules: {
        content: [
          {required: true, message: "评审意见不能为空"}
        ],
        zjkCnsIds: [
          {required: true, validator: (val) => val && val.length, message: `科研诚信承诺书不能为空`, type: "error"}
        ],
        signatureFiles: [
          {required: true, validator: (val) => val.length > 0, message: `签名不能为空`, type: "error"}
        ],
        score: [
          {required: true, validator: (val) => val >= 0, message: "大于等于0", type: "error"}
        ],
        signDate: [
          { required: true, message: "诚信承诺函签名日期不能为空"}
        ],
      },
      reviewStandard: {
        score: 100,
        name: "",
        reviewItems: []
      },
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    "reviewStandard.reviewItems": {
      deep: true,
      immediate: true,
      handler(val) {
        let totalScore = 0;
        this.reviewStandard.reviewItems.forEach(val => {
          if (!val.realScore) {
            totalScore += 0;
          } else {
            totalScore += val.realScore;
          }
        })
        this.totalScore = totalScore;
        const percent = this.getPercent(totalScore, this.reviewStandard.score)
        let recommendType = '1';
        if (percent < 70) {
          recommendType = '1'
        } else if (percent >= 70 && percent <= 90) {
          recommendType = '2'
        } else if (percent > 90) {
          recommendType = '3'
        }
        this.formData.recommendType = recommendType;
      }
    }
  },
  created() {
    this.qrcodeValue = `${window.location.origin}/online-signature/?code=${getToken()}`;
  },
  methods: {
    createTemp(){
      getFilesByUserId(this.expertUserId, this.expertUserId).then((res) => {
        const files = {}
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = []
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        if (files.signature && files.signature.length > 1) {
          files.signature.reverse()
        }
        this.formData.signatureFiles = files.signature || []
        if(this.formData.signatureFiles.length<=0){
          this.$message.error("未找到签名文件，请先手机扫码签名提交后再次点击生成。")
        }else {
          this.refreshStart = true;
          this.$api.bzh.review.zjSignPdf({signDate:this.formData.signDate}).then(res => {
            this.zjkCnsFiles = [
              {
                name: res.data.fileName,
                url: res.data.fullFilePath,
                id: res.data.id,
                filePath: res.data.filePath
              }
            ]
            this.formData.zjkCnsIds = this.zjkCnsFiles.map(val => val.id)
            this.$message.success("自动生成带签名的诚信承诺函成功！可点击预览");
            this.refreshStart = false;
            // this.refreshFile();
          }).catch((e) => {
            this.refreshStart = false;
            this.$message.error(e.toString());
          });
        }
      }).catch(e => {
        this.$message.error(e.toString())
      })


    },
    downloadTemp() {
      const elink = document.createElement('a')
      elink.href = `${VITE_FILE_DOMAIN}/view/模板/科技项目评审工作纪律的承诺.pdf`
      // elink.setAttribute('download', '科技项目管理子系统用户手册.pdf')
      elink.setAttribute('target', '_blank')
      elink.style.display = 'none'
      document.body.appendChild(elink)
      setTimeout(() => {
        elink.click()
        document.body.removeChild(elink)
      }, 66)
    },
    onChange(item) {
      if (item.realScore > item.score) {
        item.realScore = item.score;
      }
      if (item.realScore < 0) {
        item.realScore = 0;
      }
    },
    getObj() {
      Promise.all([this.$api.bzh.review.teamExpertsInfoGet(this.objId), this.$api.bzh.review.teamGet(this.teamId)]).then(res => {
        res[0].data.projectApproval = res[0].data.projectApproval || '1';
        res[0].data.signDate = res[0].data.signDate || res[1].data.reviewMeetingDate || TODAY;
        res[0].data.sysAttMainVo = res[0].data.sysAttMainVo || {sysAttMainIds: []}
        Object.assign(this.formData, res[0].data);
        if(!this.formData.recommendType){
          this.formData.recommendType = '1'
        }
        this.formData.id = this.objId;
        getFilesByUserId(this.objId, this.expertUserId).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.zjkYJFiles = files.zjkYJ || []
          this.formData.zjkYJIds = this.zjkYJFiles.map(val => val.id)
        });
        getFilesByUserId(this.teamId, this.expertUserId).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          const zjkCnsFilesNow = files.zjkCns || [];
          if(zjkCnsFilesNow.length>0){
            this.zjkCnsFiles = [zjkCnsFilesNow[0]];
          }else {
            this.zjkCnsFiles = zjkCnsFilesNow;
          }
          this.formData.zjkCnsIds = this.zjkCnsFiles.map(val => val.id)
        }).catch(e => {
          this.$message.error(e.toString())
        })
        this.loading = false;
        // if (['1'].includes(this.reviewType)) {
        //   this.$api.bzh.review.indexGet(res[1].data.indexId).then(res => {
        //     this.reviewStandard = res.data;
        //     this.reviewStandard.reviewItems.forEach((val, index) => {
        //       this.formData.projectItemScores.forEach(val2 => {
        //         if (val.id === val2.itemId) {
        //           this.$set(this.reviewStandard.reviewItems[index], "realScore", val2.score ? val2.score : 0)
        //         }
        //       })
        //     })
        //     this.loading = false;
        //   }).catch((e) => {
        //     this.loading = false;
        //     this.$message.error(e.toString());
        //   });
        // } else {
        //   this.loading = false;
        // }
      }).catch((e) => {
        this.loading = false;
        this.$message.error(e.toString());
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    onCheckSubmit() {
      // 重新计算分值
      let totalScore = 0;
      this.formData.projectItemScores = this.reviewStandard.reviewItems.map(val => {
        if (!val.realScore) {
          totalScore += 0;
        } else {
          totalScore += val.realScore;
        }
        return {itemId: val.id, score: val.realScore}
      })
      if (totalScore > this.reviewStandard.score) {
        this.$message.error(`累计总分：${totalScore} 不能大于 评审体系总分值：${this.reviewStandard.score}`);
        return false;
      }


      // 计算当前 不推荐（1）、推荐（2）、强烈推荐（3） 总分70以下默认不推荐，70-90默认推荐，90以上默认强烈推荐
      const percent = this.getPercent(totalScore, this.reviewStandard.score)
      let recommendType = '1';
      if (percent < 70) {
        recommendType = '1'
      } else if (percent >= 70 && percent <= 90) {
        recommendType = '2'
      } else if (percent > 90) {
        recommendType = '3'
      }
      this.formData.recommendType = recommendType;
      this.formData.score = totalScore;
      this.$api.bzh.review.teamExpertsInfoUpdate({
        ...this.formData,
        sysAttMainVo: {sysAttMainIds: this.formData.zjkYJIds}
      }).then(response => {
        if (this.formData.zjkCnsIds.length > 0) {
          this.$api.bzh.review.teamUpdate({
            id: this.teamId,
            sysAttMainVo: {sysAttMainIds: this.formData.zjkCnsIds}
          }).then(() => {
            if (this.formData.reviewStatus === '0') {
              this.$message.success("暂存成功");
              this.$emit("reload", 1);
              // this.$emit("update:visible", false);
            } else {
              this.$message.success("提交成功");
              this.$emit("reload", 2);
              // this.$emit("update:visible", false);
            }
          }).catch(e => {
            this.$message.error(e.toString())
          })
        } else if (this.formData.reviewStatus === '0') {
          this.$message.success("暂存成功");
          this.$emit("reload", 1);
          // this.$emit("update:visible", false);
        } else {
          this.$message.success("提交成功");
          this.$emit("reload", 2);
          // this.$emit("update:visible", false);
        }


      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    // 计算两个整数之间的百分比
    // curNum：当前数据，totalNum：总数据，isHasPercentStr：是否返回%字符
    getPercent(curNum, totalNum) {
      curNum = parseFloat(curNum);
      totalNum = parseFloat(totalNum);
      if (Number.isNaN(curNum) || Number.isNaN(totalNum)) {
        return '-';
      }
      return totalNum <= 0 ? 0 : (Math.round(curNum / totalNum * 10000) / 100.00);
    },
    onSubmit(type) {
      if (type === 1) {
        this.formData.reviewStatus = '0';
        this.onCheckSubmit()
      } else {
        this.formData.reviewStatus = '1';
        // 如果有上传意见则不校验意见
        if(this.formData.zjkYJIds.length>0){
          this.$refs.form.validate({
            fields: ['score','zjkCnsIds']
          }).then((validateResult) => {
            if (validateResult === true) {
              this.onCheckSubmit()
            } else {
              const firstError = Object.values(validateResult)[0]?.[0]?.message;
              this.$message.error(firstError);
            }
          })

        }else {
          this.$refs.form.validate().then((validateResult) => {
            if (validateResult === true) {
              this.onCheckSubmit()
            } else {
              const firstError = Object.values(validateResult)[0]?.[0]?.message;
              this.$message.error(firstError);
            }
          })
        }

      }

    },
    signature() {
      this.signDialog.open = true;
    },
    getSignFile(file) {
      if (file.id) {
        this.$api.system.user.updateUserProfile({
          sysAttMainVo: {
            sysAttMainIds: [file.id]
          }
        }).then(response => {
          this.formData.signatureFiles = [{
            name: file.fileName,
            url: file.fullFilePath,
            id: file.id,
            filePath: file.filePath
          }]
          this.$message.success('签名上传成功！')
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      } else {
        this.$message.error('签名上传失败！')
      }
    }
  }
}
</script>

<style scoped>

</style>
